package com.example.security.demo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.security.demo.constant.CommonConstant;
import com.example.security.demo.dto.UserDto;
import com.example.security.demo.service.TokenService;
import com.example.security.demo.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhanpengguo
 * @date 2019-10-15 14:53
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    RedisUtil redisUtil;

    @Override
    public String saveToken(UserDto userDto) {
        String uuid = IdUtil.simpleUUID();
        redisUtil.set(CommonConstant.ACCESS_TOKEN + userDto.getUsername(), uuid, CommonConstant.TOKEN_EXPIRE);
        redisUtil.set(uuid, JSONObject.toJSONString(userDto), CommonConstant.TOKEN_EXPIRE);
        return uuid;
    }

    @Override
    public UserDto queryUserByToken(String token) {
        String str = redisUtil.get(token);
        if (StrUtil.isEmpty(str)) {
            return null;
        }
        UserDto userDto = JSONUtil.toBean(str, UserDto.class);
        //fastjson和gson序列化会报错
//        UserDto userDto = JSONObject.parseObject(str, UserDto.class);
        return userDto;
    }

    @Override
    public void deleteToken(String token) {
        UserDto userDto = queryUserByToken(token);
        redisUtil.delete(CommonConstant.ACCESS_TOKEN + userDto.getUsername());
        redisUtil.delete(token);
    }
}
